import axios, { type InternalAxiosRequestConfig, type AxiosResponse } from "axios";
import qs from "qs";
import { useUserStoreHook } from "@/store/modules/user";
import { getAppToken, getToken } from "@/utils/auth";
import router from "@/router";
// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_SERVER,
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
  paramsSerializer: (params) => qs.stringify(params),
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 获取token
    let token: string = getAppToken();
    const requestUrl: string = config.url || "";
    // 一些选择应用后还需要用到登录token的api,比如退出登录
    if (
      requestUrl &&
      (requestUrl.includes("/openPlatform/auth/") || requestUrl.includes("/openPlatform/app/"))
    ) {
      token = getToken();
    }
    // 如果 Authorization 设置为 no-auth，则不携带 Token，用于登录、刷新 Token 等接口
    if (config.headers.Authorization !== "no-auth" && token) {
      //添加Token
      config.headers.Authorization = token;
    } else {
      delete config.headers.Authorization;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
service.interceptors.response.use(
  async (response: AxiosResponse) => {
    // 如果响应是二进制流，则直接返回，用于下载文件、Excel 导出等
    if (response.config.responseType === "blob") {
      return response;
    }
    const { statusCode, data, msg, errors } = response.data;
    // 1. 第一条拦截，返回正常的数据 对应处理不同的statusCode状态
    if (statusCode === 200) {
      return data;
    } else {
      // 根据原逻辑处理各种异常状态
      if ([500, 1001, 6008, 6005, 6011].includes(statusCode)) {
        // 验证异常
        if (msg === "ValidationException") {
          ElMessage.error(errors || "系统异常");
        } else if (statusCode === 6011) {
          ElNotification({
            title: "提示",
            message: "账号已停用",
            type: "info",
          });
          useUserStoreHook()
            .logout()
            .then(() => {
              router.push("/login");
            });
          return;
        } else {
          // 出现了数据库问题
          if (errors && errors.includes("SQLSTATE")) {
            ElMessage.error("系统异常");
          } else {
            ElMessage.error(errors || msg);
          }
        }
      } else if (statusCode === 402) {
        ElNotification({
          title: "提示",
          message: "您可能因为太久未操作，登录已过期，请重新登录",
          type: "info",
        });
        useUserStoreHook()
          .logout()
          .then(() => {
            router.push("/login");
          });
        return;
      } else {
        ElMessage.error(msg || errors || "系统异常");
      }
    }
    return Promise.reject(response || "Error");
  },
  async (error: any) => {
    // 同一个浏览器登录不同商家信息弹框的就不弹message了 直接return
    if (error == "loginUserError") {
      return Promise.reject("登录信息不一致");
    }
    const responseVal = error.response;
    const resData = responseVal ? responseVal.data : error;
    if (responseVal.status == 500 || responseVal.status == 503) {
      ElMessage.error(resData.msg || resData.data || "系统异常");
      return Promise.reject(resData);
    }
    if (error.message == "Request failed with status code 403") {
      ElNotification({
        title: "提示",
        message: "登录信息被修改，需要重新登录",
        type: "info",
      });
      useUserStoreHook()
        .logout()
        .then(() => {
          router.push("/login");
        });
      return;
    }
    ElMessage.error(resData.msg || resData.data || error.message);
    return Promise.reject(error);
  }
);

export default service;
